package com.vertx.starter.mysql;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.List;

@Log4j2
public class PlayerDao {

    protected String DB_SPLIT = "";
    protected MysqlUtil mySQLPool;

    public PlayerDao(String DB_SPLIT, MysqlUtil mySQLPool) {
        this.DB_SPLIT = DB_SPLIT;
        this.mySQLPool = mySQLPool;
    }

    public <T> void quertConfigList(String sql, Class<T> clazz, Handler<AsyncResult<List<T>>> handler) {
        mySQLPool.getConfigClient().query(sql).execute(qRes -> {
            if (qRes.succeeded()) {
                List<T> list = new ArrayList<>();

                RowSet<Row> result = qRes.result();
                List<String> col = qRes.result().columnsNames();

                for (Row row : result) {
                    JsonObject json = new JsonObject();
                    for (String str : col) {
                        json.put(str, row.getValue(str));
                    }
                    T entity = new JsonObject(json.toString()).mapTo(clazz);
                    list.add(entity);
                }
                handler.handle(Future.succeededFuture(list));
            } else {
                handler.handle(Future.failedFuture(qRes.cause()));
                log.error("-- error queryConfigList --" + sql, qRes.cause());
            }
        });
    }
}
